package com.seari.custody.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.XmlUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.word.WordUtil;
import cn.hutool.system.SystemUtil;
import com.google.api.client.util.Lists;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.seari.custody.bean.*;
import com.seari.custody.component.MinIoUtil;
import com.seari.custody.constant.MessageConstant;
import com.seari.custody.enums.MeetingFileType;
import com.seari.custody.enums.MeetingListField;
import com.seari.custody.exception.BIZException;
import com.seari.custody.pojo.MessageBean;
import com.seari.custody.service.MeetingFileService;
import com.seari.custody.service.MeetingService;
import com.seari.custody.service.MeetingUserService;
import com.seari.custody.service.UserService;
import com.seari.custody.util.JwtTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamSource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.awt.*;
import java.io.File;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.*;

import static com.seari.custody.util.JwtTokenUtils.TOKEN_HEADER;


@Slf4j
@RestController
@RequestMapping("/meeting")
public class MeetingController {
    @Autowired
    private Cache fileCache;
    @Autowired
    private MeetingService meetingService;
    @Autowired
    private UserService userService;
    @Autowired
    private MeetingFileService meetingFileService;
    @Autowired
    private MeetingUserService meetingUserService;
    @Autowired
    private MinIoUtil minIoUtil;


    /**
     * 查询打开会议的参数
     */
    @GetMapping("/openMeeting")
    public MessageBean openMeetingMetaData(String meetingId, String userNumber) {

        OpenMeeting openMeeting = meetingService.openMeeting(userNumber, meetingId);
        return MessageBean.success("查询打开会议的参数成功", openMeeting);
    }

    /**
     * 根据某年某周查询会议
     * 查询会议
     */
    @GetMapping("/list")
    public MessageBean list(String year, String week, @RequestHeader(value = TOKEN_HEADER, defaultValue = "") String token) {
        Preconditions.checkArgument(StringUtils.isNotEmpty(token), "token不能为空");
        String userNumber = JwtTokenUtils.getUserNumber(token.substring(JwtTokenUtils.TOKEN_PREFIX.length()));

        Map<String, Object> data = meetingService.getMeetingDataByYearAndWeek(userNumber, year, week);
        return MessageBean.success("查询会议成功", data);
    }

    /**
     * 根据某年某月查询会议
     * 查询会议
     */
    @GetMapping("/list/month")
    public MessageBean listOfMonth(String month, @RequestHeader(value = TOKEN_HEADER, defaultValue = "") String token) {
        Preconditions.checkArgument(StringUtils.isNotEmpty(token), "token不能为空");
        String userNumber = JwtTokenUtils.getUserNumber(token.substring(JwtTokenUtils.TOKEN_PREFIX.length()));
        Date date = DateUtil.date();
        if (!Strings.isNullOrEmpty(month)) {
            date = DateUtil.parse(month, DatePattern.NORM_MONTH_PATTERN);
        }
        return MessageBean.success("查询会议成功", meetingService.getMeetingsByMonth(userNumber, date));
    }

    /**
     * 修改会议状态
     *
     * @param id
     * @return
     */
    @GetMapping("/updMeetingStatus/{id}")
    public MessageBean readMeeting(@PathVariable Integer id) {
        Integer integer = meetingUserService.updMeetingStatus(id);
        return MessageBean.success("修改状态为已读", integer);
    }


    /**
     * 根据id更新会议
     *
     * @param meeting
     * @return
     */
    @PostMapping("/updMeeting")
    public MessageBean updMeeting(@RequestBody Meeting meeting) {
        meetingService.updateMeeting(meeting);
        return MessageBean.success("更新会议成功", meeting.getId());
    }

    /**
     * 是否参加会议
     */
    @GetMapping(value = "/attendMeeting")
    public MessageBean updateMeetingStatus(@Valid MeetingAck meetingAck) {
        Integer integer = meetingUserService.updateMeetingStatus(meetingAck);
        return MessageBean.success("", integer);
    }


    /**
     * 添加会议
     *
     * @param meeting
     * @return
     */
    @PostMapping
    public MessageBean addMeeting(@Valid @RequestBody Meeting meeting) {
        return MessageBean.success("添加会议成功", meetingService.addMeeting(meeting));
    }

    /**
     * 会议管理下载 excel
     *
     * @param response
     * @param userAgent
     * @param meetingsReq
     */
    @PostMapping("/download")
    public void downloadMeetings(HttpServletResponse response, @RequestHeader(value = "User-Agent", required = false, defaultValue = "") String userAgent, @RequestBody MeetingsReq meetingsReq) {

        List<MeetingListDTO> list = meetingService.list(meetingsReq);
        List<MeetingListDTO> newList = Lists.newArrayList();
        if (meetingsReq.getIndexList() != null) {
            for (Integer integer : meetingsReq.getIndexList()) {
                newList.add(list.get(integer - 1));
            }
        } else {
            newList = list;
        }
        String fileName = "会议列表.xlsx";
        try {
            if (
                    userAgent.toUpperCase().contains("MSIE") ||
                            userAgent.contains("Trident/7.0")) {
                fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            } else {
                fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            }
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            try (ExcelWriter writer = ExcelUtil.getBigWriter(); ServletOutputStream out = response.getOutputStream();
            ) {
                for (Integer field : meetingsReq.getFields()) {
                    MeetingListField meetingListField = MeetingListField.byIndex(field);
                    writer.addHeaderAlias(meetingListField.getField(), meetingListField.getFieldName());
                }
                //只输出设置别名的列
                writer.setOnlyAlias(true);
                if (meetingsReq.getFields().size() > 1) {
                    writer.merge(meetingsReq.getFields().size() - 1, "安全保护区会议记录");
                }
                writer.write(newList, true);
                for (int i = 0; i < writer.getColumnCount(); i++) {
                    writer.autoSizeColumn(i);
                    int columnWidth = writer.getSheet().getColumnWidth(i);
                    //autoSize 英文有效
                    writer.setColumnWidth(i, columnWidth * 17 / 10 / 256);
                }

                writer.flush(out, true);
            }
        } catch (Exception e) {
            throw new BIZException("下载文件失败", e);
        }
    }

    @PostMapping("/listMeetings")
    public MessageBean meetings(@RequestBody MeetingsReq meetingsReq) {
        //清除缓存
        if (Objects.equals("1", meetingsReq.getRefresh())) {
            meetingService.refreshMeetingList();
        }

        List<MeetingListDTO> data = meetingService.list(meetingsReq);

        Integer pageSize = meetingsReq.getPageSize();
        Integer pageIndex = meetingsReq.getPageIndex();
        Map<String, Object> result = Maps.newHashMap();
        int size = data.size();
        int i = size / pageSize;
        int pages = size % pageSize == 0 ? i : i + 1;
        pageIndex = Math.min(pages, pageIndex);

        int from = pageSize * (pageIndex - 1);
        from = Math.max(0, from);
        int to = from + pageSize;

        result.put("pages", pages);
        result.put("total", size);
        result.put("data", data.subList(from, Math.min(size, to))
        );
        return MessageBean.success("获取会议列表成功", result);
    }

    /**
     * 根据id查询会议
     *
     * @return
     */

    @GetMapping(value = "/detail/{meetingId}")
    public MessageBean getMeetingDetail(@PathVariable String meetingId) {

        HashMap<String, Object> stringObjectHashMap = meetingService.qryDetailByMeetingId(meetingId);
        return MessageBean.success("查询会议成功", stringObjectHashMap);
    }

    /**
     * 根据id查询会议
     *
     * @param id
     * @return
     */

    @GetMapping(value = "/{id}")
    public MessageBean getMeeting(@PathVariable String id, @RequestHeader(value = TOKEN_HEADER, defaultValue = "") String token) {
        Preconditions.checkArgument(StringUtils.isNotEmpty(token), "token不能为空");
        String userNumber = JwtTokenUtils.getUserNumber(token.substring(JwtTokenUtils.TOKEN_PREFIX.length()));
        Meeting meeting = meetingService.selectCzHrtableById(id, userNumber);
        return MessageBean.success("查询会议成功", meeting);
    }

    /**
     * 删除会议
     */
    @GetMapping(value = "/delete/{id}")
    public MessageBean deleteMeeting(@PathVariable String id, @RequestHeader(value = TOKEN_HEADER, defaultValue = "") String token) {
        Preconditions.checkArgument(StringUtils.isNotEmpty(token), "token不能为空");
        String userNumber = JwtTokenUtils.getUserNumber(token.substring(JwtTokenUtils.TOKEN_PREFIX.length()));
        int i = meetingService.deleteMeeting(id, userNumber);
        return MessageBean.success("删除会议成功", i);
    }

    /**
     * 批量删除
     */
    @PostMapping("/deleteMeetings")
    public MessageBean deleteMeetings(@RequestBody String[] ids, @RequestHeader(value = TOKEN_HEADER, defaultValue = "") String token) {
        Preconditions.checkArgument(StringUtils.isNotEmpty(token), "token不能为空");
        String userNumber = JwtTokenUtils.getUserNumber(token.substring(JwtTokenUtils.TOKEN_PREFIX.length()));
        Preconditions.checkArgument(CollectionUtil.isNotEmpty(Arrays.asList(ids)), "ids不能为空");
        Integer integer = meetingService.deleteMeetingIds(ids, userNumber);
        return MessageBean.success("删除会议成功", integer);
    }


    /**
     * 根据日期获取线下内部会议室信息
     *
     * @param date
     * @return
     */
    @GetMapping(value = "/offlineMeetings/{date}")
    MessageBean offLineMeetings(@PathVariable String date) {
        Map<String, List<OAMeetingInfo>> offlineMeetings = meetingService.getOfflineMeetings(date);
        HashMap<String, List<OAMeetingInfo>> result = Maps.newHashMap();
        offlineMeetings.forEach((k, v) -> {
            if (!(k.contains("19楼") || k.contains("集团"))) {
                result.put(k, v);
            }
        });
        return MessageBean.success("获取线下内部会议室信息成功", result);
    }

    /**
     * 根据日期获取线下外部会议室信息
     */
    @GetMapping(value = "/externalSites/{date}")
    MessageBean externalSites(@PathVariable String date) {
        Map<String, List<OAMeetingInfo>> offlineMeetings = meetingService.getOfflineMeetings(date);
        Set<String> strings = offlineMeetings.keySet();
        HashMap<String, List<OAMeetingInfo>> result = Maps.newHashMap();
        offlineMeetings.forEach((k, v) -> {
            if (k.contains("19楼") || k.contains("集团")) {
                result.put(k, v);
            }
        });
        return MessageBean.success("获取线下外部会议室信息成功", result);
    }

    /**
     * 线下外部会议地址模糊搜索
     *
     * @param key
     * @return
     */
    @GetMapping(value = "/offlineOuterSites")
    MessageBean offlineOuterSites(String key) {
        if (Strings.isNullOrEmpty(key)) {
            return MessageBean.success("查询关键字不可为空", "");
        }
        return MessageBean.success("获取线下会议室信息成功", meetingService.offlineOuterSites(key));
    }

    /**
     * 微信消息推送测试
     *
     * @param message
     * @return
     */
    @RequestMapping(value = "/push")
    public MessageBean weChatMessagePush(String message) {
        String result = meetingService.weChatMessagePush(message);
        return new MessageBean(MessageConstant.SUCCESS_TYPE, MessageConstant.SUCCESS, "", result);
    }

    /**
     * 会议备忘录保存
     */
    @PostMapping(value = "/note")
    public MessageBean note(String note, String meetingId, @RequestHeader(value = TOKEN_HEADER, defaultValue = "") String token) {
        Preconditions.checkArgument(StringUtils.isNotEmpty(token), "token不能为空");
        String userNumber = JwtTokenUtils.getUserNumber(token.substring(JwtTokenUtils.TOKEN_PREFIX.length()));
        Font font = new Font("宋体", 0, 16);

        String fileName = String.format("会议备忘录-%s.docx", userNumber);
        try (XWPFDocument doc = WordUtil.getWriter().addText(font, note).getDoc();
             ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream(); BufferedOutputStream output = new BufferedOutputStream(arrayOutputStream);) {
            doc.write(output);
            output.flush();
            InputStreamSource inputStreamSource = new ByteArrayResource(arrayOutputStream.toByteArray());
            String extName = "docx";
            MeetingFile meetingFile = new MeetingFile();
            meetingFile.setId(IdUtil.objectId());
            String path = IdUtil.objectId() + "." + extName;
            minIoUtil.putObject(MinIoUtil.MEETING_BUCKET, path, inputStreamSource.getInputStream());
            meetingFile.setFileType(MeetingFileType.MEETING_NOTE.getCode());
            meetingFile.setFilePath(path);
            meetingFile.setUserNumber(userNumber);
            meetingFile.setMeetingId(meetingId);
            meetingFile.setFileExt(extName);
            meetingFile.setFileName(fileName);

            meetingFileService.uploadFile(meetingFile);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return MessageBean.success("保存会议备忘成功");
    }

    @PostMapping("/update/meetingSummary")
    public MessageBean updateMeetingSummary(String id, String data) {
        meetingFileService.updateMeetingSummary(id, data);
        return MessageBean.success("更新会议纪要成功");
    }

    /**
     * 会议相关文件上传
     */

    @GetMapping("/upload/{meetingId}/{fileType}")
    public MessageBean upload(@RequestParam("file") MultipartFile[] files, @PathVariable String meetingId, @RequestHeader(value = TOKEN_HEADER, defaultValue = "") String token, @PathVariable String fileType) {
        Preconditions.checkArgument(StringUtils.isNotEmpty(token), "token不能为空");
        String userNumber = JwtTokenUtils.getUserNumber(token.substring(JwtTokenUtils.TOKEN_PREFIX.length()));
        for (MultipartFile file : files) {
            try (InputStream inputStream = file.getInputStream();) {
                String ext = FileNameUtil.getSuffix(file.getOriginalFilename());
                String id = IdUtil.objectId() + "." + ext;
                minIoUtil.putObject(MinIoUtil.MEETING_BUCKET, id, inputStream, file.getContentType());
                MeetingFile meetingFile = new MeetingFile();
                meetingFile.setId(IdUtil.objectId());
                meetingFile.setFileType(fileType);
                meetingFile.setMeetingId(meetingId);
                meetingFile.setFileName(file.getOriginalFilename());
                meetingFile.setFilePath(id);
                meetingFile.setFileExt(ext);
                meetingFile.setUserNumber(userNumber);
                meetingFileService.uploadFile(meetingFile);
            } catch (Exception e) {
                return MessageBean.success("文件上传失败");
            }
        }
        return MessageBean.success("文件上传成功");
    }

    /**
     * 根据会议id 和文件类型下载
     *
     * @param response
     * @param userAgent
     * @param id
     * @param type
     */
    @GetMapping("/download/{type}/{id}")
    public void download(HttpServletResponse response, @RequestHeader(value = "User-Agent", required = false, defaultValue = "") String userAgent, @PathVariable String id, @PathVariable String type) {
        MeetingFile meetingFile = meetingFileService.downloadMeetingFile(type, id);
        downFile(response, userAgent, meetingFile);
    }

    /**
     * 根据文件id下载
     *
     * @param response
     * @param userAgent
     * @param id
     */
    @GetMapping("/download/{id}")
    public void downloadById(HttpServletResponse response, @RequestHeader(value = "User-Agent", required = false, defaultValue = "") String userAgent, @PathVariable String id) {
        MeetingFile meetingFile = meetingFileService.qryMeetingFileById(id);
        downFile(response, userAgent, meetingFile);
    }


    private void downFile(HttpServletResponse response, @RequestHeader(value = "User-Agent", required = false, defaultValue = "") String userAgent, MeetingFile meetingFile) {
        String fileName = "";
        try (InputStream inputStream = minIoUtil.getObject(MinIoUtil.MEETING_BUCKET, meetingFile.getFilePath())) {
            if (
                    userAgent.toUpperCase().contains("MSIE") ||
                            userAgent.contains("Trident/7.0")) {
                fileName = java.net.URLEncoder.encode(meetingFile.getFileName(), "UTF-8");
            } else {
                fileName = new String(meetingFile.getFileName().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            }
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            response.setCharacterEncoding("UTF-8");
            IoUtil.copy(inputStream, response.getOutputStream());
        } catch (Exception e) {
            throw new BIZException("下载文件失败", e);
        }
    }

    /**
     * 会议下所有文件
     *
     * @param meetingId
     * @return
     */
    @GetMapping("/files/{meetingId}")
    public MessageBean meetingFiles(@PathVariable String meetingId) {

        List<MeetingFile> meetingFiles = meetingFileService.qryByMeetingId(meetingId);

        return MessageBean.success("获取回文件列表成功", meetingFiles);
    }

    /**
     * 查询所有音频和转写文件
     *
     * @param meetingId
     * @return
     */
    @GetMapping("/voices/{meetingId}")
    public MessageBean getVoiceAndTexts(@PathVariable String meetingId) {
        List<MeetingVoiceDTO> voices = meetingFileService.getVoices(meetingId);
        return MessageBean.success("获取所有音频成功", voices);
    }

    /**
     * 获取会议id通过projectId
     *
     * @param projectId
     * @return
     */
    @GetMapping("/ids/{projectId}")
    public MessageBean getMeetingIdByProjectId(@PathVariable String projectId) {

        List<Meeting> ids = meetingService.qryMeetingIdByProjectId(projectId);
        return MessageBean.success("获取会议ID成功", ids);
    }

    /**
     * 删除文件逻辑删除
     *
     * @param id
     * @return
     */
    @GetMapping("/file/delete/{id}")
    public MessageBean deleteByFileId(@PathVariable String id) {

        meetingFileService.delete(id);
        return MessageBean.success("删除文件成功");
    }

    /**
     * 分片是否上传
     *
     * @param fileChunk
     * @return
     */
    @GetMapping("/upload/chunk")
    public ResponseEntity<MessageBean> checkPartFile(FileChunk fileChunk) {
        String userNumber = fileChunk.getUserNumber();
        try {
            Object o = fileCache.get("part_" + userNumber + "_" + fileChunk.getChunkNumber() + "_" + fileChunk.getFilename());
            if (ObjectUtil.isNotEmpty(o)) {
                return ResponseEntity.ok(MessageBean.success("文件上传成功"));
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResponseEntity.badRequest().body(MessageBean.fail("文件不存在"));
        }

        return ResponseEntity.badRequest().body(MessageBean.success("文件不存在"));
    }

    /**
     * 分片上传接口
     *
     * @param fileChunk
     * @return
     */
    @PostMapping("/upload/chunk")
    public ResponseEntity<MessageBean> upload(FileChunk fileChunk) {

        if (fileChunk.getFile().isEmpty()) {

            return ResponseEntity.ok(MessageBean.success("文件上传不可为空"));
        }
        String filePath = "part_" + fileChunk.getUserNumber() + "_" + fileChunk.getChunkNumber() + "_" + fileChunk.getFilename();

        File tempFile = null;
        try {
            String s = SystemUtil.get(SystemUtil.FILE_SEPARATOR) + "upload" + SystemUtil.get(SystemUtil.FILE_SEPARATOR) + filePath;

            tempFile = FileUtil.file(".", s);

            FileUtil.writeBytes(fileChunk.getFile().getBytes(), tempFile);

        } catch (Exception e) {
            FileUtil.del(tempFile);
            log.error(e.getMessage(), e);
            return ResponseEntity.badRequest().body(MessageBean.fail("文件上传失败"));
        }
        fileCache.putIfAbsent(filePath, tempFile.getAbsolutePath());
        return ResponseEntity.ok(MessageBean.success("文件上传成功"));
    }

    /**
     * 合并分片接口
     *
     * @param fileChunk
     * @return
     */
    @PostMapping("/upload/chunk/merge")
    public ResponseEntity<MessageBean> merge(FileChunk fileChunk) {
        String userNumber = fileChunk.getUserNumber();
        String filename = fileChunk.getFilename();
        Integer totalChunks = fileChunk.getTotalChunks();
        File tempFile = FileUtil.file(".", SystemUtil.get(SystemUtil.FILE_SEPARATOR) + "upload" + SystemUtil.get(SystemUtil.FILE_SEPARATOR) + filename);
        long totalSize = 0;
        try (RandomAccessFile targetFile = new RandomAccessFile(tempFile, "rw");) {
            Integer i = 1;
            for (; i <= totalChunks; i++) {
                targetFile.seek(totalSize);
                File file = FileUtil.file(".", SystemUtil.get(SystemUtil.FILE_SEPARATOR) + "upload" + SystemUtil.get(SystemUtil.FILE_SEPARATOR) + "part_" + userNumber + "_" + i + "_" + fileChunk.getFilename());
                try (FileInputStream fis = new FileInputStream(file);) {
                    byte[] bytes = new byte[1024 * 100];
                    int r;
                    while ((r = fis.read(bytes)) != -1) {
                        targetFile.write(bytes, 0, r);
                    }
                    long fileSize = file.length();
                    totalSize += fileSize;
                }
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(MessageBean.fail("文件上传失败"));
        }

        if (!Objects.equals(SecureUtil.md5(tempFile), fileChunk.getIdentifier())) {
            return ResponseEntity.badRequest().body(MessageBean.fail("文件上传失败"));
        }
        for (Integer i = 1; i <= totalChunks; i++) {
            fileCache.evict("part_" + userNumber + "_" + i + "_" + fileChunk.getFilename());
        }
        UploadVideoVO uploadVideoVO = new UploadVideoVO(tempFile, fileChunk.getMeetingId(), userNumber);
//        meetingService.uploadMeetingVideo(uploadVideoVO);
        ThreadUtil.execAsync(() -> meetingService.uploadMeetingVideo(uploadVideoVO));

        return ResponseEntity.ok(MessageBean.success("文件上传成功"));
    }

    public static void main(String[] args) {
        String html = "<p>烦烦烦说法是</p><p><strong>fdfsdfsffsfsdf</strong></p><p><strong>ffdasfdsf</strong></p><p><em>fsfsfsfssd</em></p>";

        String textContent = XmlUtil.parseXml(html).getTextContent();
        System.out.println(textContent);


//        try {
        html = "<html><body>" + html + "</body></html>";
        File file1 = FileUtil.file(".", "1.docx");
        WordUtil.getWriter(file1).addText(new Font("宋体", 22, 22), html).flush();


//　　bais = new ByteArrayInputStream();
//　　poifs = new POIFSFileSystem();
//　　DirectoryEntry directory = poifs.getRoot();
//　　//WordDocument名称不允许修改
//　　directory.createDocument("WordDocument", bais);
//　　ostream = new FileOutputStream(uuid);
//　　poifs.writeFilesystem(ostream);//当前目录下就生成了一个测试.doc的文档
//        } catch (Exception e) {
//　　logger.error("exception is {}", e);
//        } finally {
//　　IOUtils.closeQuietly(poifs);
//　　IOUtils.closeQuietly(ostream);
//　　IOUtils.closeQuietly(bais);
//　　try {
//　　　　FileUtils.forceDelete(file);
//　　} catch (Exception e2) {
//　　}
//        }
//
//    }
    }
}